package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.PlaylistAdapter;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PlaylistItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.MonthDayEvent;
import com.jdy.haoduoai.view.OnMonthDayClickListener;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.view.RippleView.OnRippleCompleteListener;
import com.jdy.haoduoai.view.WeekCalendar;
import com.jdy.haoduoai.view.swipemenu.SwipeMenu;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuCreator;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuItem;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuListView;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

/**
 * 宝宝故事单
 * 
 * @author hufei
 * 
 */
public class MyPlaylistActivity extends BaseActivity {

  @SuppressWarnings("unused")
  private final static String TAG = MyPlaylistActivity.class.getSimpleName();

  private final static String TITLE_TAG = "宝宝故事单";

  @InjectView(id = R.id.weekCalendar)
  private WeekCalendar mWeekCalendar;

  private String mSelectedDate;

  @InjectView(id = R.id.swipe_listview)
  private SwipeMenuListView mSwipeListView;

  // private int mUserId = -1;

  private int mSelectedId = -1;

  private List<PlaylistItem> mPlaylistItems = new ArrayList<PlaylistItem>();

  @InjectView(id = R.id.imageView1)
  private ImageView defaultImageView;

  @InjectView(id = R.id.pushToMachineRippleView)
  private RippleView mPushStoryRippleView;

  private PlaylistAdapter mAdapter;

  private LeUser mLeUser;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_playlist_layout);
    setTitle(TITLE_TAG);

    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }

    initView();
  }

  @SuppressWarnings("unchecked")
  private List<PlaylistItem> getValueList(String selectedDate) {
    this.mSelectedDate = selectedDate;
    SharedPreferences prefs = this.getSharedPreferences(Constant.PLAYLIST,
        Context.MODE_PRIVATE);
    String result = prefs.getString(selectedDate, "");
    if (Tools.isNotEmpty(result)) {
      List<PlaylistItem> playlist = (List<PlaylistItem>) JsonSerializer
          .getInstance().deserialize(result, ArrayList.class,
              PlaylistItem.class);
      return playlist;
    } else {
      return null;
    }
  }

  private void playvideo(final int sid, final int uid) {
    new CustomAsyncTask(MyPlaylistActivity.this, new IAsyncTask() {

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {

        if (result.isSuccess()) {
          DateUtils.showToast(MyPlaylistActivity.this, "已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            DateUtils.showToast(MyPlaylistActivity.this, "已推送到设备播放");
//          } else {
//            DateUtils.showToast(MyPlaylistActivity.this, "未连接到设备，请检查设备联网情况！");
//          }

        } else {
          LeConfig.isDeviceConnect = false;
          DateUtils.showToast(MyPlaylistActivity.this, "设备不在线");
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        int volume = -1, minutes = -1;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
       // param_.put("mode", "im");

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        if (uid != -1) {
          param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void initView() {

    mPushStoryRippleView
        .setOnRippleCompleteListener(new OnRippleCompleteListener() {
          @Override
          public void onComplete(RippleView rippleView) {
            if (mSelectedId != -1) {
              playvideo(mSelectedId, -1);
            } else {
              DateUtils.showToast(MyPlaylistActivity.this, "请选择一个条目");
            }
          }
        });

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    String todayDate = formatter.format(new java.util.Date());

    mPlaylistItems = getValueList(todayDate);

    if (mPlaylistItems != null && !mPlaylistItems.isEmpty()) {
      mAdapter = new PlaylistAdapter(this, mPlaylistItems);
      defaultImageView.setVisibility(View.GONE);
    } else {
      mAdapter = new PlaylistAdapter(this, new ArrayList<PlaylistItem>());
    }

    Calendar todayCal = Calendar.getInstance();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    mSelectedDate = sdf.format(todayCal.getTime());

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    mWeekCalendar.setmDisplayMetrics(dm);
    mWeekCalendar.setOnMonthDayClickListner(new OnMonthDayClickListener() {

      @Override
      public void onMonthDayClick(MonthDayEvent mde) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String strDate = sdf.format(mde.Cal.getTime());
        // DateUtils.showToast(getApplicationContext(), strDate);
        // updateSwipeListView(strDate);
        mPlaylistItems = getValueList(strDate);
        if (mPlaylistItems != null && mPlaylistItems.size() != 0) {
          mAdapter.setData(mPlaylistItems);
          mSwipeListView.setVisibility(View.VISIBLE);
          defaultImageView.setVisibility(View.GONE);
        } else {
          defaultImageView.setVisibility(View.VISIBLE);
          mSwipeListView.setVisibility(View.GONE);
        }
      }
    });

    mSwipeListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    mSwipeListView.setAdapter(mAdapter);

    // step 1. create a MenuCreator
    SwipeMenuCreator creator = new SwipeMenuCreator() {

      @Override
      public void create(SwipeMenu menu, int pos) {
        // create "delete" item
        SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
        // set item background
        deleteItem
            .setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
        // set item width
        deleteItem.setWidth(dp2px(90));
        // set a icon
        deleteItem.setIcon(R.drawable.ic_delete);
        // add to menu
        menu.addMenuItem(deleteItem);
      }
    };

    mSwipeListView.setMenuCreator(creator);

    // step 2. listener item click event
    mSwipeListView
        .setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
          @Override
          public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
            switch (index) {
            case 0:
              // delete
              deleteByPosition(position);
              mAdapter.notifyDataSetChanged();
              break;
            }
            return false;
          }
        });

    // set SwipeListener
    mSwipeListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

      @Override
      public void onSwipeStart(int position) {
        // swipe start
      }

      @Override
      public void onSwipeEnd(int position) {
        // swipe end
      }

      @Override
      public void onClickSwipeOpen(int position) {
        // TODO Auto-generated method stub

      }
    });

    // other setting
    // listView.setCloseInterpolator(new BounceInterpolator());

    // test item long click
    mSwipeListView.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
          long arg3) {

        arg1.setPressed(true);
        PlaylistItem item = (PlaylistItem) arg0.getItemAtPosition(arg2);
        mSelectedId = item.EpisodeId;
      }
    });

  }

  private int dp2px(int dp) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
        getResources().getDisplayMetrics());
  }

  protected void deleteByPosition(int position) {

    mPlaylistItems.remove(position);
    SharedPreferences prefs = this.getSharedPreferences(Constant.PLAYLIST,
        Context.MODE_PRIVATE);
    String jsonString = JsonSerializer.getInstance().serialize(mPlaylistItems);
    prefs.edit().putString(mSelectedDate, jsonString).apply();
    mAdapter.setData(mPlaylistItems);
    if (mPlaylistItems != null && mPlaylistItems.size() != 0) {
      mAdapter.setData(mPlaylistItems);
      mSwipeListView.setVisibility(View.VISIBLE);
      defaultImageView.setVisibility(View.GONE);
    } else {
      defaultImageView.setVisibility(View.VISIBLE);
      mSwipeListView.setVisibility(View.GONE);
    }
  }

  // private class PlaylistAdapter extends BaseAdapter {
  //
  // private List<PlaylistItem> playlistItems;
  //
  // private final Context context;
  //
  // private PlaylistAdapter(Context c, List<PlaylistItem> data) {
  // this.context = c;
  // this.playlistItems = data;
  // }
  //
  // public void setData(List<PlaylistItem> playlist) {
  //
  // this.playlistItems = playlist;
  // notifyDataSetChanged();
  // }
  //
  // public void removeByPosition(int position) {
  // if (playlistItems != null && position >= 0 && position < getCount()) {
  // playlistItems.remove(position);
  // notifyDataSetChanged();
  // }
  // }
  //
  // @Override
  // public int getCount() {
  //
  // return playlistItems.size();
  // }
  //
  // @Override
  // public PlaylistItem getItem(int position) {
  //
  // return playlistItems.get(position);
  // }
  //
  // @Override
  // public long getItemId(int position) {
  //
  // return position;
  // }
  //
  // @Override
  // public View getView(int position, View convertView, ViewGroup parent) {
  //
  // final PlaylistItem item = getItem(position);
  // ViewHolder holder;
  // if (convertView == null) {
  // LayoutInflater li = (LayoutInflater) context
  // .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  // convertView = li.inflate(R.layout.listitem_playlist, parent, false);
  // holder = new ViewHolder();
  // holder.subtitleTv = (TextView) convertView
  // .findViewById(R.id.episodeNameTextView);
  // holder.orderTv = (TextView) convertView
  // .findViewById(R.id.orderTextView);
  // holder.timeRangeTv = (TextView) convertView
  // .findViewById(R.id.rangeTimeTextView);
  // holder.collectionNameTv = (TextView) convertView
  // .findViewById(R.id.collectionNameTextView);
  // convertView.setTag(holder);
  // } else {
  // holder = (ViewHolder) convertView.getTag();
  // }
  // // ((SwipeListView) parent).recycle(convertView, position);
  //
  // holder.subtitleTv.setText(item.SubTitle);
  // holder.orderTv.setText("第" + item.Order + "集");
  // holder.timeRangeTv.setText("" + item.TimeRange);
  // holder.collectionNameTv.setText(item.CollectionTitle);
  //
  // return convertView;
  // }
  // }
  //
  // private class ViewHolder {
  // TextView subtitleTv;
  // TextView orderTv;
  // TextView timeRangeTv;
  // TextView collectionNameTv;
  // }

}
